package com.library.controller;

import com.library.entity.User;
import com.library.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private RegisterService registerService;

    @GetMapping
    public String showRegisterPage() {
        return "register";
    }

    @PostMapping
    public String register(User user, HttpSession session, Model model) {
        User result = registerService.register(user);
        if (result != null) {
            session.setAttribute("id", result.getId());
            session.setAttribute("isLogin", true);
            session.setAttribute("userName",result.getUserName());
            session.setMaxInactiveInterval(60 * 60 * 72);
            return "redirect:/home";
        } else {
            model.addAttribute("errMsg","用户名已存在或格式不规范!");
            return "register";
        }
    }
}
